import { createRouter, createWebHashHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
    {
        path: '/',
        redirect: '/movies'
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/auth/LoginView.vue'),
        meta: { requiresGuest: true }
    },
    {
        path: '/register',
        name: 'register',
        component: () => import('@/views/auth/RegisterView.vue'),
        meta: { requiresGuest: true }
    },
    {
        path: '/movies',
        name: 'movies',
        component: () => import('@/views/movies/MovieListView.vue')
    },
    {
        path: '/movies/add',
        name: 'add-movie',
        component: () => import('@/views/movies/AddMovieView.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/movies/:id',
        name: 'movie-detail',
        component: () => import('@/views/movies/MovieDetailView.vue'),
        props: true
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const authStore = useAuthStore()

    if (to.meta.requiresAuth && !authStore.user) {
        next({
            name: 'login',
            query: { redirect: to.fullPath }
        })
    } else if (to.meta.requiresGuest && authStore.user) {
        next({ name: 'movies' })
    } else {
        next()
    }
})

export default router